package utils

import (
	"encoding/json"
	"gin-admin/common/dto/response"
	"gin-admin/global"
	"reflect"

	"github.com/jinzhu/copier"
)

func ModelToStruct(toValue, fromValue interface{}) *response.ServiceError {
	if err := copier.Copy(toValue, fromValue); err != nil {
		message := response.GetStatusCode(response.FailedCode).Message
		global.GA_LOGGER.Sugar().Errorw("数据映射发成错误", "error", err)
		return response.WrapError(response.FailedCode, message)
	}
	return nil
}

func StructToMapWithoutZero(input interface{}) (map[string]interface{}, *response.ServiceError) {
	jsonData, err := json.Marshal(input)
	if err != nil {
		return nil, response.WrapError(response.FailedCode, response.GetStatusCode(response.FailedCode).Message)
	}
	var result map[string]interface{}
	if err := json.Unmarshal(jsonData, &result); err != nil {
		return nil, response.WrapError(response.FailedCode, response.GetStatusCode(response.FailedCode).Message)
	}
	cleanMap(result)
	return result, nil
}

func cleanMap(data map[string]interface{}) {
	for key, value := range data {
		if value == nil || reflect.ValueOf(value).IsZero() {
			delete(data, key)
			continue
		}
		if nestedMap, ok := value.(map[string]interface{}); ok {
			cleanMap(nestedMap)
			if len(nestedMap) == 0 {
				delete(data, key)
			}
		}
	}
}
